package nobu.nakata.nfcfare.datamapper;

import java.util.Collection;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import net.sf.jsr107cache.Cache;
import nobu.nakata.nfcfare.table.ILongCollectionKeyEntity;


public class LongCollectionDataMapper<T extends ILongCollectionKeyEntity> {
	private Cache cache;
	private PersistenceManager pm;
	private Class<T> klass;
	private String typeName;
	private String collectionName;
	
	public LongCollectionDataMapper(Cache cache, PersistenceManager pm, Class<T> klass, 
			String collectionName) {
		this.cache			= cache;
		this.pm				= pm;
		this.klass			= klass;
		this.typeName		= klass.getSimpleName();
		this.collectionName	= collectionName;
	}
	
	public Collection<T> findByLongCollection(Long collectionKey) {
		String cacheKey = makeCacheKey(collectionKey);
		Collection<T> stored = (Collection<T>) cache.get(cacheKey);
		if (stored != null)
			return stored;
		stored = loadFindByLongCollection(collectionKey);
		if (stored == null)
			return null;
		cache.put(cacheKey, stored);
		return stored;
	}
	private Collection<T> loadFindByLongCollection(Long collectionKey) {
		Query qKlass = pm.newQuery(klass);
		qKlass.setFilter(collectionName + " == pCollectionKey");
		qKlass.declareParameters("Long pCollectionKey");
		try {
			return pm.detachCopyAll((Collection<T>) qKlass.execute(collectionKey));
		} finally {
			qKlass.closeAll();
		}
	}
	
	public T set(T item) {
		cache.remove(makeCacheKey(item.getCollectionKey()));
		return pm.detachCopy(pm.makePersistent(item));
	}
	
	private String makeCacheKey(Long busCode) {
		return typeName + ":" + busCode;
	}
}
